package xian.woniuxy.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import xian.woniuxy.annotation.RequirePermissions;
import xian.woniuxy.domain.ResultVo;
import xian.woniuxy.entity.User;
import xian.woniuxy.service.RoleService;
import xian.woniuxy.service.UserService;

import java.util.List;
import java.util.Map;

/**
 * @author gao
 * @date 2023/07/03 11:31:58
 */
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @RequirePermissions("user:save")
    @PostMapping("user/save")
    public ResultVo save(@RequestBody User user) {
        int rows = userService.save(user);
        return rows > 0 ? ResultVo.success() : ResultVo.failure();
    }

    @RequirePermissions("user:update")
    @PostMapping("user/update")
    public ResultVo update(@RequestBody User user) {
        int rows = userService.update(user);
        return rows > 0 ? ResultVo.success() : ResultVo.failure();
    }

    @RequirePermissions("user:find")
    @PostMapping("user/findAll")
    public ResultVo findAll() {
        List<User> list = userService.findAll();
        return ResultVo.success(list);
    }

    @RequirePermissions("user:delete")
    @PostMapping("user/delete")
    public ResultVo delete(@RequestBody String userId) {
        if (!StringUtils.hasText(userId)) {
            throw new RuntimeException("userId is null");
        }
        int rows = userService.delete(Integer.valueOf(userId));
        return rows > 0 ? ResultVo.success() : ResultVo.failure();
    }

    @RequirePermissions("user:find")
    @PostMapping("user/findOne")
    public ResultVo findOne(@RequestBody String userId) {
        if (!StringUtils.hasText(userId)) {
            throw new RuntimeException("userId is null");
        }
        Integer id = Integer.valueOf(userId);
        User user = userService.findOne(id);
        return ResultVo.success(user);
    }

    @RequirePermissions("user:update")
    @PostMapping("user/distributeRoles")
    public ResultVo distributeRoles(@RequestBody Map map) {
        Integer userId = (Integer) map.get("userId");
        List<Integer> roleIds = (List<Integer>) map.get("roleIds");
        int rows = userService.distributeUserRoles(userId, roleIds);
        return rows > 0 ? ResultVo.success() : ResultVo.failure();
    }
}
